package org.lds.message.center.email;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.lds.message.center.common.MessageHandler;
import org.lds.message.center.common.model.request.EmailRequest;
import org.lds.message.center.email.properties.EmailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@RequiredArgsConstructor
public class EmailHandler implements MessageHandler<EmailRequest> {
    private final EmailProperties emailProperties;
    private final JavaMailSender mailSender;

    @Override
    public void handle(EmailRequest request) throws Exception {
        if (!emailProperties.isDebug()) {
            MimeMessage message = message(request);
            mailSender.send(message);
        }

        log.info("邮件发送成功. request={}", request);
    }

    private MimeMessage message(EmailRequest request) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, request.isMultipart());
        helper.setFrom(emailProperties.getFrom());
        helper.setTo(request.getTo());
        if (ArrayUtils.isNotEmpty(request.getCc())) {
            helper.setCc(request.getCc());
        }
        if (ArrayUtils.isNotEmpty(request.getBcc())) {
            helper.setCc(request.getBcc());
        }
        helper.setSubject(request.getSubject());
        helper.setText(request.getText(), request.isHtml());

        if (request.isMultipart()) {
            for (EmailRequest.Attachment attachment : request.getAttachments()) {
                helper.addAttachment(attachment.getFilename(),
                        () -> Files.newInputStream(Paths.get(attachment.getFileAddress())),
                        "application/octet-stream");
            }
        }
        return message;
    }
}
